package com.kaibes.web.util;

import java.lang.reflect.Method;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.HeadersRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

//TODO @Component
public class HeaderUtils {

    @Autowired
    private RequestMappingHandlerMapping requestMappingHandlerMapping;

    public String getHeadersFromMethod(Method method) {
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = requestMappingHandlerMapping.getHandlerMethods();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> map : handlerMethods.entrySet()) {
            HandlerMethod handlerMethod = map.getValue();
            if (method == handlerMethod.getMethod()) {
                RequestMappingInfo info = map.getKey();
                HeadersRequestCondition headerCondition = info.getHeadersCondition();
                String headers = headerCondition.toString();
                if (headers != null && headers.startsWith("[") && headers.endsWith("]")) {
                    headers = headers.substring(1, headers.length() - 1);
                    return headers;
                }
            }
        }
        return "";
    }
}
